<?php
namespace app\wxapp\controller;

use app\index\controller\Base;
use think\Request;

/**
 * 数据接口
 * @package app\wxapp\controller
 */
class Api extends Base{

    //protected $api_hosts = 'http://318.ogmall.com';
    protected $api_hosts = 'http://xcx.ogmall.com:8080';

    protected $request_param = [
        'token'=>'',
    ];

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $key = 'ogmall-small-program';
        $this->request_param['token'] = $this->getEncrypt($key);
    }


    /**
     * 获取指定品牌id下的 产品
     * @param Request $request
     */
    public function getProduct(Request $request){
        $query = $request->param();
        if(!$query['id']){
            $this->error('没有数据','',[]);
        }
        if(empty($query['categotyId'])){
            unset($query['categotyId']);//兼容接口
        }
        $api = $this->createApi("/api/brand/products",$query);
        $res = $this->curl($api);
        $this->success("获取成功",'',$res);
    }



    public function getCategory(Request $request){
        $query = $request->param();

        if(!$query['id']){
            $this->error('没有数据','',[]);
        }

        $api = $this->createApi("/api/products/categorys",$query);
        $res = $this->curl($api);
        $this->success("获取成功",'',$res);
    }


    /**
     * 产生api地址
     * @param $path
     * @param $data
     * @return string
     */
    protected function createApi($path,$data){
        $api    = $this->api_hosts.$path;
        foreach($data as $key=> $val ){
            $this->request_param[$key] = $this->getEncrypt($val);
        }
        $query  = http_build_query($this->request_param);
        $api   .= "?".$query;

        return $api;
    }

    /**
     * post 请求
     * @param $url
     * @return mixed
     */
    protected function curl($url){
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);

        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        $post_data = array(); //没有这个东东还真不行 不知道为什么
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        return $data;

    }

    /**
     * 接口加密
     * @param string $data
     * @return string
     */
    public function getEncrypt($data){
        $result = exec('/usr/etc/jdk1.8.0_151/bin/java AES '.$data,$encrypt,$return_var);
        return $result;
    }


}